package im.starchat.chat.activity.publish;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.squareup.picasso.Picasso;
import com.tencent.TIMGroupManager;
import com.tencent.TIMValueCallBack;
import com.tencent.av.sdk.AVError;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import butterknife.ButterKnife;
import butterknife.InjectView;
import im.starchat.chat.R;
import im.starchat.chat.XLApplication;
import im.starchat.chat.activity.AvActivity;
import im.starchat.chat.activity.BaseActivity;
import im.starchat.chat.control.QavsdkControl;
import im.starchat.chat.rest.RestClient;
import im.starchat.chat.rest.model.RoomBean;
import im.starchat.chat.rest.model.api.UpTokenResponse;
import im.starchat.chat.utils.BitmapHelp;
import im.starchat.chat.utils.Constants;
import im.starchat.chat.utils.FileUtils;
import im.starchat.chat.utils.ImageConstant;
import im.starchat.chat.utils.ImageUtil;
import im.starchat.chat.utils.PreferencesStorageUtil;
import im.starchat.chat.utils.RetrofitErrorUtil;
import im.starchat.chat.utils.UserUtils;
import im.starchat.chat.utils.Util;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * 创建直播的页面
 */
public class ReleaseLiveActivity extends BaseActivity implements TextWatcher, View.OnClickListener {
    private static final String TAG = "ReleaseLiveActivity";
    public static final int MAX_TIMEOUT = 5 * 1000;
    public static final int MSG_CREATEROOM_TIMEOUT = 1;
//    private static String IMAGE_FILE_LOCATION = "file:///sdcard/temp.jpg";


    // 设置头像
    private final static int SELECT_PIC_KITKAT = 3;
    private final static int SELECT_PIC = 4;
    private final static int REQ_CODE_PHOTO_CROP = 5;
    private final static int REQ_CODE_CAMERA = 6;
    private static final String SAVE_AVATORNAME = "live.jpeg";// 保存的图片名

    private int mCreateRoomErrorCode = AVError.AV_OK;
    private Context ctx = null;
    private QavsdkControl mQavsdkControl;
    //        private UserInfo mSelfUserInfo;
    private Uri mCameraImageUri, mImageUri;
    private XLApplication mXLApplication;
    private EditText mEditTextLiveTitle;
    @InjectView(R.id.live_cover)
    ImageView mImageButtonLiveCover;
    //    private ImageButton mImageButtonCloseLiveCover;
    private Button mButtonShow;
    private String mLiveTitleString;
    private String paradeCoverPath;
    private int roomNum;
    //    private String userPhone = "123";
    private String groupid;
    @InjectView(R.id.set_background)
    TextView mSetBackground;
    @InjectView(R.id.close)
    ImageView mCloseBtn;
    File mFile;

    private String mImageKey = "";

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_CREATEROOM_TIMEOUT:
                    if (mQavsdkControl != null) {
                        mQavsdkControl.setCreateRoomStatus(false);
                        mQavsdkControl.setCloseRoomStatus(false);
                        refreshWaitingDialog();
                        Toast.makeText(ctx, R.string.notify_network_timeout, Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    break;
            }
            return false;
        }
    });

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
//            if (mSelfUserInfo.isCreater() == true) {
            String action = intent.getAction();
            if (action.equals(Util.ACTION_CREATE_ROOM_NUM_COMPLETE)) {//第一步点击直播按钮根据房间号创建房间
                //本地加入创建房间
                createRoom(roomNum);
            } else if (action.equals(Util.ACTION_ROOM_CREATE_COMPLETE)) {//第二步创建房间后发广播创建群聊
                //加入房间的回调
                Log.d(TAG, "create room complete");
                mHandler.removeMessages(MSG_CREATEROOM_TIMEOUT);
                refreshWaitingDialog();
                mCreateRoomErrorCode = intent.getIntExtra(
                        Util.EXTRA_AV_ERROR_RESULT, AVError.AV_OK);


                if (mCreateRoomErrorCode == AVError.AV_OK) {
                    createGroup();//创建群聊方法
                } else {
                    //showDialog(DIALOG_CREATE_ROOM_ERROR);
                    Log.e(TAG, "创建房间失败");
                }
            } else if (action.equals(Util.ACTION_CREATE_GROUP_ID_COMPLETE)) {//创建好后进入直播Activity
                System.out.println("ACTION_CREATE_GROUP_ID_COMPLETE-------------->");


                createLive();
                Constants.isCreater = true;//只有创建直播的人才是true
                //进去直播界面
                startActivityForResult(new Intent(ReleaseLiveActivity.this, AvActivity.class)
                        .putExtra(Util.EXTRA_ROOM_NUM, roomNum) //room
                        .putExtra(Util.EXTRA_SELF_IDENTIFIER, PreferencesStorageUtil.getUserId(ReleaseLiveActivity.this))
                        .putExtra(Util.EXTRA_GROUP_ID, groupid), 0);
                finish();
            } else if (action.equals(Util.ACTION_CLOSE_ROOM_COMPLETE)) {
            }
        }
//        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.release_live_activity);
        ButterKnife.inject(this);
        mXLApplication = (XLApplication) getApplication();
        registerBroadcastReceiver();
        mImageKey = PreferencesStorageUtil.getUserId(ReleaseLiveActivity.this) + System.currentTimeMillis() + ".jpg";
        paradeCoverPath = ImageConstant.ROOT_DIR + mImageKey;
        initData();
        initViewUI();
    }

    private void initData() {
        File galleryFile = new File(XLApplication.catchDir + "/" + "icon"
                + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()));
        mImageUri = Uri.fromFile(galleryFile);

        File cameraFile = new File(XLApplication.cameraDir, new SimpleDateFormat("yyyyMMdd-HHmmss")
                .format(new Date()) + ".jpg");
        mCameraImageUri = Uri.fromFile(cameraFile);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        unregisterBroadcastReceiver();
    }


    private void registerBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Util.ACTION_ROOM_CREATE_COMPLETE);
        intentFilter.addAction(Util.ACTION_CLOSE_ROOM_COMPLETE);
        intentFilter.addAction(Util.ACTION_CREATE_GROUP_ID_COMPLETE);
        intentFilter.addAction(Util.ACTION_CREATE_ROOM_NUM_COMPLETE);
        registerReceiver(mBroadcastReceiver, intentFilter);
    }

    private void unregisterBroadcastReceiver() {
        if (mBroadcastReceiver != null)
            unregisterReceiver(mBroadcastReceiver);
    }

    private void initViewUI() {
        mEditTextLiveTitle = (EditText) findViewById(R.id.live_title);
        mButtonShow = (Button) findViewById(R.id.btn_show);
        if(!TextUtils.isEmpty(UserUtils.getUserInstance().getAvatar())){
            Picasso.with(ReleaseLiveActivity.this).load(UserUtils.getUserInstance().getAvatar())
                    .placeholder(R.drawable.home_bg)
                    .into(mImageButtonLiveCover);

        }
        mButtonShow.setOnClickListener(this);
        mEditTextLiveTitle.setOnClickListener(this);
        mEditTextLiveTitle.addTextChangedListener(this);
        mSetBackground.setOnClickListener(this);
        mCloseBtn.setOnClickListener(this);
        ctx = this;
        XLApplication mXLApplication = (XLApplication) getApplication();
        mQavsdkControl = mXLApplication.getQavsdkControl();
        if(!mQavsdkControl.hasAVContext()){
            startContext();
        }
    }

    private int mLoginErrorCode =  AVError.AV_OK;
    private void startContext() {
        if (!mQavsdkControl.hasAVContext()) {

//            String phone = mSelfUserInfo.getUserPhone();
//            //if (mSelfUserInfo.getLoginType() == Util.TRUSTEESHIP)
//            phone = "86-" + phone;
//            Log.e(TAG, "import phone: " + phone+ "Usersig "+ mSelfUserInfo.getUsersig());
//
//
//            mLoginErrorCode = mQavsdkControl.startContext(
//                    phone, mSelfUserInfo.getUsersig());
            mLoginErrorCode = mQavsdkControl.startContext(
                    PreferencesStorageUtil.getUserId(ReleaseLiveActivity.this), PreferencesStorageUtil.getTsig(ReleaseLiveActivity.this));
            Log.e(TAG, "startContext mLoginErrorCode   " +mLoginErrorCode);
            if (mLoginErrorCode !=  AVError.AV_OK) {
                Log.e(TAG, "startContext mLoginErrorCode   " + mLoginErrorCode);
//                showDialog(DIALOG_LOGIN_ERROR);
            }
//            refreshWaitingDialog();
        }
    }

    @Override
    public void onClick(View v) {
        String coverName = null;
        switch (v.getId()) {
            case R.id.live_cover:
            case R.id.set_background:
                onUserImageClick();
                break;
            case R.id.btn_show:
                if(roomNum>0){
                  createRoomNum();
                }else{
                  ctx.sendBroadcast(new Intent(Util.ACTION_CREATE_ROOM_NUM_COMPLETE));
                }
                break;
            case R.id.close:
                finish();
                break;
            default:
                break;
        }
    }

    private void onUserImageClick() {
        if(FileUtils.isSDCardMounted()){
            showOptionsDialog();
        }else{
            toast("没有安装SD卡!", Toast.LENGTH_SHORT);
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        Constants.isPublish = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        Constants.isPublish = true;
    }

    /**
     * 将头像保存在SDcard
     */
    public void saveMyBitmap(Bitmap bitmap)
    {
        if(FileUtils.createOrExistsFolder(ImageUtil.getImageCachePath())){
            File f = new File(ImageUtil.getImageCachePath(),
                    SAVE_AVATORNAME);
            try
            {
                f.createNewFile();
                FileOutputStream fOut = new FileOutputStream(f);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);

                fOut.flush();
                fOut.close();
                mFile = f;
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }

    }


    // 选择图片来源
    private void showOptionsDialog()
    {
        String[] items = new String[] { "拍照", "选择本地图片" };

        DialogInterface.OnClickListener click = new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                switch (which)
                {
                    case 0://拍照
                        Intent camera = new Intent("android.media.action.IMAGE_CAPTURE");
                        camera.putExtra("output", mCameraImageUri);
                        startActivityForResult(camera, REQ_CODE_CAMERA);
                        break;
                    case 1://选择本地图片

                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                            intent.addCategory(Intent.CATEGORY_OPENABLE);
                            intent.setType("image/jpeg");
                            startActivityForResult(intent, SELECT_PIC_KITKAT);
                        } else {
                            Intent intent = new Intent();
                            intent.setType("image/*");
                            intent.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(intent, SELECT_PIC);
                        }
                        break;
                }
            }
        };

        new AlertDialog.Builder(this).setItems(items,
                click).show();
    }



    boolean hasPic = false;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode)
        {

            case SELECT_PIC_KITKAT:
                // 从相册返回
                if(data != null){
                    Uri localUri = data.getData();
                    if (localUri == null) {
                        return;
                    }
                    String path = BitmapHelp.getPath(this, localUri);
                    System.out.println("SELECT_PIC_KITKAT--path->" + path);
                    if(!TextUtils.isEmpty(path)){
                        Uri uri = Uri.fromFile(new File(path));
                        readLocalImage(uri);
                    }
                }

                break;
            case SELECT_PIC:
                // 从相册返回
                if(data != null){
                    Uri mUri = data.getData();
                    System.out.println("SELECT_PIC_KITKAT--mUri->" + mUri.getAuthority() + "   " +  mUri.getPath());
                    if (mUri == null) {
                        return;
                    }
                    readLocalImage(mUri);
                }
                break;
            case REQ_CODE_CAMERA:
                // 从相机返回,从设置相机图片的输出路径中提取数据
                readLocalImage(mCameraImageUri);
                break;
            case REQ_CODE_PHOTO_CROP:
                System.out.println("REQ_CODE_PHOTO_CROP--mImageUri.getPath()-> " + mImageUri.getPath());
                Bitmap bitmap = BitmapFactory.decodeFile(mImageUri.getPath());
                saveMyBitmap(bitmap);
                System.out.println("REQ_CODE_PHOTO_CROP--bitmap-> " + (bitmap == null));
                hasPic = true;
                mImageButtonLiveCover.setImageBitmap(bitmap);
                break;

//            case IMAGE_REQUEST_CODE:
//                startPhotoZoom(data.getData());
//                break;
//            case CAMERA_REQUEST_CODE:
//                startPhotoZoom(Uri.fromFile(new File(ImageUtil.getImageCachePath(), SAVE_AVATORNAME)));
//                break;
//            case RESULT_REQUEST_CODE:
//                if (data != null)
//                {
//                    Bundle extras = data.getExtras();
//                    if (extras != null)
//                    {
//                        Bitmap photo = extras.getParcelable("data");
//                        saveMyBitmap(photo); // 保存裁剪后的图片到SD
//                        hasPic = true;
//                        mImageButtonLiveCover.setImageBitmap(photo);
//                    }
//                }
//                break;
        }

    }

    private void readLocalImage(Uri uri) {
        if (uri != null) {
            startPhotoCrop(uri, REQ_CODE_PHOTO_CROP); // 图片裁剪
        }
    }

    private void startPhotoCrop(Uri uri, int reqCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 600);
        intent.putExtra("outputY", 600);
        intent.putExtra("output", mImageUri);
        intent.putExtra("return-data", false);
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, reqCode);
    }



    /**
     * 加入直播房间
     *
     * @param roomNum 讨论房间号
     */
    private void createRoom(int roomNum) {
        if (Util.isNetworkAvailable(ctx)) {
            int room = roomNum;
//            if (mSelfUserInfo.getEnv() == Util.ENV_TEST) {
////                room = Integer.parseInt(mSelfUserInfo.getUserPhone().substring(0, 5));
//                room = 14010;
//            }
            mQavsdkControl.enterRoom(room);
            mHandler.sendEmptyMessageDelayed(MSG_CREATEROOM_TIMEOUT, MAX_TIMEOUT);
            Toast.makeText(ctx, "正在创建视频房间中...", Toast.LENGTH_SHORT).show();
            refreshWaitingDialog();
        } else {
            Toast.makeText(ctx, getString(R.string.notify_no_network), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * IMSDK创建聊天室
     */
    private void createGroup() {
        Log.d(TAG, "createGroup");
        ArrayList<String> list = new ArrayList<String>();
        list.add(PreferencesStorageUtil.getUserId(ReleaseLiveActivity.this));
        String group_name = mEditTextLiveTitle.getText().toString();
        if(TextUtils.isEmpty(group_name)){
            group_name = mEditTextLiveTitle.getHint().toString();
        }
        TIMGroupManager.getInstance().createGroup("ChatRoom", list, group_name, new TIMValueCallBack<String>() {
            @Override
            public void onError(int i, String s) {
                Log.e(TAG, "create group failed: " + i + " :" + s);
                Toast.makeText(ctx, "创建群失败:" + i + ":" + s, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(String s) {
                Log.d(TAG, "create group succ: " + s);
                groupid = s;//群号id
                ctx.sendBroadcast(new Intent(Util.ACTION_CREATE_GROUP_ID_COMPLETE));//发广播
            }
        });
    }

//    /**
//     * 同步个人信息到后台
//     */
//    public void createLive() {
//        new Thread() {
//            @Override
//            public void run() {
//                super.run();
//                JSONObject object = new JSONObject();
//                try {
//                    object.put(Util.EXTRA_ROOM_NUM, roomNum);
//                    object.put(Util.EXTRA_USER_PHONE, userPhone);
//                    object.put(Util.EXTRA_LIVE_TITLE, mLiveTitleString);
//                    object.put(Util.EXTRA_GROUP_ID, groupid);
//                    object.put("imagetype", 2);
//                    Log.d(TAG, "userServer testhere " + roomNum + " phone " + userPhone + " roomtitle " + mLiveTitleString);
//                    System.out.println(object.toString());
//                    ImageUtil tool = new ImageUtil();
//
////                    int ret = tool.sendCoverToServer(coverPath, object, HttpUtil.liveImageUrl, "livedata");
//                    int ret = tool.sendCoverToServer(paradeCoverPath, object, HttpUtil.testliveImageUrl, "livedata");
//                    Log.i(TAG, "userServer upload roomInfo to server " + " " + ret);
//                    if (ret == 200) {
//                        ctx.sendBroadcast(new Intent(Util.ACTION_INSERT_ROOM_TO_SERVER_COMPLETE));
//                        mXLApplication.setHandleMemberRoomSuccess(true);
//                        Log.i(TAG, "userServer upload roomInfo to server success " + " " + ret);
//                    } else {
//                        Log.e(TAG, "testhere " + " " + ret);
//                    }
//
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
//            }
//        }.start();
//    }

    public void createLive() {

        if(TextUtils.isEmpty(mLiveTitleString)){
            mLiveTitleString = mEditTextLiveTitle.getHint().toString();
        }
        if(hasPic){//是否上传头像 上传头像后把头像上传到七牛
            XLApplication.getInstance().getRestClient().upToken("zhibo/" + mImageKey, new Callback<UpTokenResponse>() {
                @Override
                public void success(UpTokenResponse nullResponse, Response response) {
                    if(RetrofitErrorUtil.handleResponse(ReleaseLiveActivity.this, response)){
                        return;
                    }
                    UploadManager uploadManager = new UploadManager();
                    uploadManager.put(ImageUtil.getImageCachePath() + "/" + SAVE_AVATORNAME, "zhibo/" + mImageKey, nullResponse.getUptoken(),
                            new UpCompletionHandler() {
                                @Override
                                public void complete(String key, ResponseInfo info, JSONObject response) {

                                    Log.d(TAG, "key--->" + key);
                                    Log.d(TAG, "ResponseInfo--->" + info.statusCode);
                                    Log.d(TAG, "response--->" + response.toString());
//                                String id, String name, String description, int duration,
//                                String end_at, String tencent_group_id,
//                                        String tencent_file_id, String status, Callback<RoomBean> callback

                                    XLApplication.getInstance().getRestClient().putFeedInfo(roomNum + "", mLiveTitleString, mLiveTitleString, RestClient.BASE_IMG_URL + key , 0, null, groupid, null, "online", new Callback<RoomBean>() {
                                        @Override
                                        public void success(RoomBean roomBean, Response response) {
                                            toast("正在发起直播", Toast.LENGTH_SHORT);
                                            ctx.sendBroadcast(new Intent(Util.ACTION_INSERT_ROOM_TO_SERVER_COMPLETE));
                                            mXLApplication.setHandleMemberRoomSuccess(true);
                                            finish();
                                        }

                                        @Override
                                        public void failure(RetrofitError error) {
                                            toast("发布直播失败", Toast.LENGTH_SHORT);
                                            finish();
                                        }
                                    });
//                                    Log.i("qiniu", info);
                                }
                            }, null);
                }

                @Override
                public void failure(RetrofitError error) {

                }
            });
        }else{
            XLApplication.getInstance().getRestClient().putFeedInfo(roomNum + "", mLiveTitleString, mLiveTitleString, UserUtils.getUserInstance().getAvatar() , 0, null, groupid, null, "online", new Callback<RoomBean>() {
                @Override
                public void success(RoomBean roomBean, Response response) {
                    toast("正在发起直播", Toast.LENGTH_SHORT);
                    ctx.sendBroadcast(new Intent(Util.ACTION_INSERT_ROOM_TO_SERVER_COMPLETE));
                    mXLApplication.setHandleMemberRoomSuccess(true);
                    finish();
                }

                @Override
                public void failure(RetrofitError error) {
                    toast("发布直播失败", Toast.LENGTH_SHORT);
                    finish();
                }
            });
        }



    }


    /**
     * 向后台申请房间号
     */
    public void createRoomNum() {

        XLApplication.getInstance().getRestClient().postZhibo(mLiveTitleString, "", "", new Callback<RoomBean>() {
            @Override
            public void success(RoomBean roomBean, Response response) {
                roomNum = roomBean.getId();
                if(roomNum > 0){
                    ctx.sendBroadcast(new Intent(Util.ACTION_CREATE_ROOM_NUM_COMPLETE));
                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });


//
//        new Thread() {
//            @Override
//            public void run() {
//                super.run();
//
//
//                String response = HttpUtil.PostUrl(HttpUtil.createRoomNumUrl, new ArrayList<NameValuePair>());
//                Log.d(TAG, "createRoomNum response" + response);
//                if (!response.endsWith("}")) {
//                    Log.e(TAG, "onSmsRegisterInfo response is not json style" + response);
//                    return;
//                }
//                JSONTokener jsonTokener = new JSONTokener(response);
//                try {
//                    JSONObject object = (JSONObject) jsonTokener.nextValue();
//                    int ret = object.getInt(Util.JSON_KEY_CODE);
//                    Log.d(TAG, "" + ret);
//                    if (ret != HttpUtil.SUCCESS) {
//                        Toast.makeText(ctx, "error:" + ret, Toast.LENGTH_SHORT).show();
//                        return;
//                    }
//                    JSONObject dataJsonObject = object.getJSONObject(Util.JSON_KEY_DATA);
//                    roomNum = dataJsonObject.getInt("num");
//                    Log.d(TAG, "roomnum = " + roomNum);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//                //发消息表示已经创建好房间
//                ctx.sendBroadcast(new Intent(Util.ACTION_CREATE_ROOM_NUM_COMPLETE));
//            }
//        }.start();
    }

    public void takePhoto(String name) {
        File outputImage = new File(Environment.getExternalStorageDirectory(), name);
        ImageConstant.PhotoClassflag = ImageConstant.COVER;
        File destDir = new File(ImageConstant.ROOT_DIR);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ImageConstant.imageuri = Uri.fromFile(outputImage);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, ImageConstant.imageuri);
        startActivityForResult(intent, ImageConstant.TAKE_PHOTO);
    }


    @Override
    public void afterTextChanged(Editable s) {
        mLiveTitleString = mEditTextLiveTitle.getText().toString();
//        mButtonShow.setEnabled(mLiveTitleString != null && mLiveTitleString.length() > 0);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    private void refreshWaitingDialog() {

    }

    /**
     * 把Uri 转换成bitmap
     *
     * @param uri
     * @return
     */
    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            // 先通过getContentResolver方法获得一个ContentResolver实例，
            // 调用openInputStream(Uri)方法获得uri关联的数据流stream
            // 把上一步获得的数据流解析成为bitmap
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }
}
